/**
 * 
 */
package com.explgo.backend.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.explgo.backend.domain.User;
import com.explgo.backend.jpa.UserRepository;
import com.explgo.backend.service.UserService;

/**
 * The user service implementation.
 * 
 * @author Jialiang(Cain) Wang
 * 
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserRepository userDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.explgo.backend.service.UserService#save(com.explgo.backend.domain
	 * .User)
	 */
	@Override
	public User save(User user) {
		return userDao.save(user);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.explgo.backend.service.UserService#getCurrentUser()
	 */
	@Override
	public User getCurrentUser() {
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();

		if (auth != null) {
			Object principal = auth.getPrincipal();

			if (principal instanceof User) {
				User user = (User) auth.getPrincipal();
				return userDao.findOne(user.getId());
			}
		}

		return null;
	}

}
